﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SPStyleCop.Test.Util
{
    /// <summary>
    /// PathUtility tools for all unit test.
    /// This class has been created using ideas from http://contribstylecop.codeplex.com 
    /// Some simplification may have been made from the original version.
    /// </summary>
    public static class PathUtility
    {
        public static string GetCommonRootPath(IEnumerable<string> paths)
        {
            string[] commonPathParts = null;
            int commonPartIndex = int.MaxValue;

            foreach (string path in paths)
            {
                if (!Path.IsPathRooted(path))
                {
                    throw new InvalidOperationException("Only fully qualified path are supported");
                }

                string[] pathParts = path.Split(Path.DirectorySeparatorChar);

                if (commonPathParts == null)
                {
                    commonPathParts = pathParts;
                    commonPartIndex = commonPathParts.Length;
                }
                else
                {
                    int partIndex = 0;
                    while (partIndex < pathParts.Length && partIndex < commonPathParts.Length)
                    {
                        if (commonPathParts[partIndex].ToUpperInvariant() != pathParts[partIndex].ToUpperInvariant()) break;

                        partIndex++;
                    }

                    commonPartIndex = Math.Min(commonPartIndex, partIndex);
                }
            }

            string commonPath;
            if (commonPartIndex == 0)
            {
                commonPath = string.Empty;
            }
            else if (commonPartIndex == 1)
            {
                commonPath = string.Concat(commonPathParts[0], Path.DirectorySeparatorChar);
            }
            else
            {
                commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonPathParts, 0, commonPartIndex);
            }

            return commonPath;
        }
    }
}
